import JSONPath from 'jsonpath'

export const utils = {}

utils.productJson = function (originalData, rules) {
  if (_.isEmpty(originalData) || _.isEmpty(rules))
    return {}
  const result = {}
  _.each(rules, (value, key) => {
    let defaultValue = ''
    if (_.isNumber(key)) {
      key = value.key
      defaultValue = value.default
      value = value.value
    }
    key = utils.getPath(key)
    value = utils.getPath(value)
    value = value ? (JSONPath.query(originalData, value, 1)[0] || defaultValue) : defaultValue
    JSONPath.value(result, key, value)
  })
  return result
}

utils.getPath = function (key) {
  if (_.isEmpty(key))
    return key
  if (!key.startsWith('$.')) {
    return '\$.' + key
  }
  return key
}

utils.format = function (str, kwargs) {
  str = str.replace(/\{(\w+)\}/g, function (substring, args) {
    console.log(args, kwargs)
    return kwargs[args]
  })
  return str
}


